package com.mianyang.zhangsan.common.util;

import com.mianyang.zhangsan.common.constant.SecConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author jiangjr
 * @date 2022-12-18
 */
@Component
public class CacheHelper {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public String cacheKey(String codeType) {
        return SecConstant.CACHE_KEY_PREFIX + codeType;
    }

    public String cacheKey(String codeType, String codeValue) {
        return SecConstant.CACHE_KEY_PREFIX + codeType + SecConstant.CACHE_KEY_SEPARATE + codeValue;
    }

    public void addValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void addList(String key, List<Object> values) {
        redisTemplate.opsForList().leftPushAll(key, values);
    }

    public void addValue(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void setExpire(String key, long expire) {
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    public Boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }
}
